import Taro from '@tarojs/taro-rn';
import * as tslib_1 from "tslib";
import React from 'react';
import { Component } from "@tarojs/taro-rn";
import { View, Image, Text, RichText } from "@tarojs/components-rn";
import { AtToast, AtTabs, AtTabsPane } from "taro-ui";
import { getRuntime, htmlToText, pageSize, ServerHost, servicePhoneNumber } from "../../utils/common";
import { toJS } from 'mobx';
import { inject, observer } from "@tarojs/mobx-rn";
import detailStyleSheet from "./detail_styles";

import share from '../../assets/img/icon_46.png';
import tel from '../../assets/img/icon_47.png';
import time_long from '../../assets/img/icon_48.png';
import iconCollection from "../../assets/img/icon_03.png";
import iconCollection_on from "../../assets/img/icon_03_on.png";
import share_icon from "../../assets/img/share_arrow.png";
import close_icon from "../../assets/img/icon_close_bold.png";
var _styleSheet = detailStyleSheet;

function _getClassName() {
  var className = [];
  var args = arguments[0];
  var type = Object.prototype.toString.call(args).slice(8, -1).toLowerCase();

  if (type === 'string') {
    args = args.trim();
    args && className.push(args);
  } else if (type === 'array') {
    args.forEach(function (cls) {
      cls = _getClassName(cls).trim();
      cls && className.push(cls);
    });
  } else if (type === 'object') {
    for (var k in args) {
      k = k.trim();

      if (k && args.hasOwnProperty(k) && args[k]) {
        className.push(k);
      }
    }
  }

  return className.join(' ').trim();
}

function _getStyle(classNameExpression) {
  var className = _getClassName(classNameExpression);

  var classNameArr = className.split(/\s+/);
  var style = [];

  if (classNameArr.length === 1) {
    style.push(_styleSheet[classNameArr[0].trim()]);
  } else {
    classNameArr.forEach(function (cls) {
      style.push(_styleSheet[cls.trim()]);
    });
  }

  return style;
}

let Detail = class Detail extends Component {
  constructor(props) {
    super(props);

    this.getJsApiParam = () => {
      let currentUrl = window.location.href;
      let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`;
      Taro.showLoading({ title: '加载中...' });
      fetch(apiUrl, {
        method: 'GET',
        mode: "cors",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        credentials: 'same-origin'
      }).then(response => {
        Taro.hideLoading();
        return response.json();
      }).then(response => {
        let appId = response.appId;
        let timestamp = response.timestamp;
        let nonceStr = response.nonceStr;
        let signature = response.signature;
        this.setState({ wxConfig: response });
        wx.config({
          debug: false,
          appId: appId,
          timestamp: timestamp,
          nonceStr: nonceStr,
          signature: signature,
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      }).catch(error => {
        console.log(error);
      });
    };

    this.play = () => {
      let videoContext = Taro.createVideoContext('taroVideo');
      videoContext.seek(this.state.currentTime);
    };

    this.pause = () => {
      this.setState({ currentPlayVideoId: -1 });
    };

    this.fullscreen = () => {
      let videoContext = Taro.createVideoContext('taroVideo');
      videoContext.requestFullScreen({ direction: 90 });
    };

    this.stop = () => {
      this.setState({ currentPlayVideoId: -1 });
    };

    this.requestFullScreen = e => {
      this.state.videoContext.requestFullScreen();
    };

    this.state = {
      pageIndex: 1,
      pageSize,
      items: [],
      totalCount: 0,
      courseInformation: {},
      courseId: 1,
      currentNavId: 0,
      isCollection: false,
      isTips: false,
      tipsText: '',
      courseInfo: {},
      videoSrc: null,
      //videoSrc: 'http://ynjwt.ynxbgg.net/Video//c7069922-52ec-4a64-9326-864481f62c4d.mp4',
      current: 0,
      isShare: false,
      autoplay: false,
      currentPlayVideoId: -1,
      chapterQueryType: 1,
      videoContext: null,
      currentTime: 0
    };
    // 配置微信分享
  }
  componentWillMount() {
    Taro.setNavigationBarTitle({ title: '课程详情' });
    let id = parseInt(this.$router.params.id);
    let chapterQueryType = getRuntime().getToken() ? 2 : 1;
    this.getJsApiParam();
    this.setState({
      courseId: id,
      chapterQueryType
    }, () => {
      this.getCourseInformation();
      this.getCourseChapterInfo();
    });
    let isCollection = parseInt(this.$router.params.isCollection);
    if (isCollection === 1) {
      this.setState({ isCollection: true });
    }
  }
  componentDidMount() {
    const videoContext = Taro.createVideoContext('taroVideo');
    this.setState({
      videoContext: videoContext
    });
  }
  handelRouter(url = '/pages/index/index') {
    getRuntime().navigateTo(url);
  }
  makePhone(phone) {
    if (!phone) {
      phone = servicePhoneNumber;
    }
    getRuntime().makePhoneCall(phone);
  }
  changeNavId(id) {
    this.setState({ currentNavId: id });
  }
  scrollChangeNavId(e) {
    this.setState({ currentNavId: e.detail.current || 0 });
  }
  getCourseInformation() {
    let businessSchool = this.props.stores.BusinessSchool;
    businessSchool.getCourseInformation({
      id: this.state.courseId,
      callback: res => {
        // console.log(res)
        let isCollection = parseInt(this.$router.params.isCollection) === 1 ? true : toJS(res.isCollection);
        this.setState({
          courseInformation: res,
          isCollection
        }, () => {
          this.share();
        });
      }
    });
  }
  getCourseChapterInfo() {
    let businessSchool = this.props.stores.BusinessSchool;
    let { courseId, pageIndex, pageSize, chapterQueryType } = this.state;
    businessSchool.getCourseChapterInfo({
      formType: chapterQueryType,
      courseId,
      pageIndex,
      pageSize,
      callback: res => {
        if (res.items) {
          let videoSrc = res.items[0]['url'];
          this.setState({ videoSrc });
        }
        if (pageIndex === 1) {
          this.setState({ totalCount: toJS(res.totalCount), items: toJS(res.items) });
        } else {
          const { items } = this.state;
          items.push(...(res.items || []));
          this.setState({ totalCount: res.totalCount, items });
        }
      }
    });
  }
  getMore() {
    let { totalCount, pageSize, pageIndex } = this.state;
    const { loading } = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getCourseChapterInfo();
      });
    }
  }
  toggleCollection() {
    if (!getRuntime().getToken()) {
      getRuntime().navigateTo('/pages/login/login');
      return;
    }
    let { userStore } = this.props.stores;
    this.setState({
      isCollection: !this.state.isCollection
    }, () => {
      if (this.state.isCollection) {
        // 收藏
        userStore.saveUserCollection({
          form: {
            courseInformationId: parseInt(this.$router.params.id),
            userCollectionType: '3'
          }
        });
      } else {
        // 取消收藏
        userStore.cancelUserCollection({
          form: {
            id: parseInt(this.$router.params.id),
            userCollectionType: '3'
          },
          callback: () => {
            // this.setState({isTips: true, tipsText: '取消收藏成功~'})
          }
        });
      }
    });
  }
  getChapterId(id) {
    if (id < 10) {
      id = '0' + id;
    }
    return id;
  }
  setVideoSrc(url, index) {
    if (!url) {
      getRuntime().showToast('视频不存在或已下架~');
      return;
    }
    this.setState({
      videoSrc: url,
      autoplay: true,
      currentPlayVideoId: -1
    }, () => {
      //this.state.videoContext.play()
    });
    /*var isIphone = navigator.userAgent.indexOf('iPhone') >= 0;
    console.log(navigator.userAgent)
    if (isIphone) {
      window.location.href = url
    }else {
      this.setState({
        videoSrc: url,
        autoplay: true,
        currentPlayVideoId: index
      })
    }*/
  }
  handleClick(value) {
    this.setState({
      current: value
    });
  }
  // 购买课程
  buyCourse(courseChapterId = null) {
    if (!getRuntime().getToken()) {
      getRuntime().navigateTo('/pages/login/login');
      return;
    }
    getRuntime().showModal('您确定要购买此课程吗?', '', () => {
      let { courseId } = this.state;
      let { BusinessSchool } = this.props.stores;
      if (!courseId) {
        getRuntime().showToast('参数错误~');
        return;
      }
      if (courseChapterId === 'all') {
        courseChapterId = null;
      }
      BusinessSchool.buyCourse({
        form: {
          courseInfoId: courseId,
          courseChapterId
        },
        callback: res => {
          getRuntime().wxPay(res, () => {
            Taro.showModal({
              title: '购买成功，请前往(我的-我的课程)中查看',
              content: '',
              confirmText: '立即前往'
            }).then(res => {
              if (res.confirm) {
                getRuntime().navigateTo('/pages/user/course');
              }
            });
          });
        }
      });
    });
  }
  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let item = this.state.courseInformation;
    let url1 = ServerHost + '/m/#/pages/business_school/detail?id=' + item.id;
    let title = item.courseName;
    let desc = htmlToText(item.courseContent);
    let imgUrl = item.courseLogoImg;
    var shareData = {
      title,
      desc,
      imgUrl,
      otherImgUrl: '',
      url: window.location.href,
      link: window.location.href
    };
    wx.ready(function () {
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
    // WxShare(url,item.logo,item.title,partOf(item.content, 30))
  }
  btnShare() {
    this.setState({
      autoplay: false,
      currentPlayVideoId: -1,
      isShare: true
    });
  }
  onClose() {
    this.setState({ isShare: false });
  }
  componentDidHide() {
    this.setState({ isShare: false });
  }
  // 组件状态监听事件
  endedVideo() {
    this.setState({ currentPlayVideoId: -1 });
  }
  // 组件状态监听事件
  pauseVideo() {
    this.setState({ currentPlayVideoId: -1 });
  }
  onTimeUpdate(e) {
    let currentTime = e.detail.currentTime;
    this.setState({ currentTime });
    // if(currentTime>this.state.currentTime) {
    //   this.setState({currentTime})
    // }else {
    //   //alert(currentTime)
    // }
  }
  fullscreenChange() {
    let { currentTime } = this.state;
    let videoContext = Taro.createVideoContext('taroVideo');
    console.log('全屏监听~');
    // console.log(currentTime)
    console.log(videoContext);
    alert(currentTime);
    videoContext.seek(currentTime);
    //alert(currentTime+'&'+JSON.stringify(videoContext))
    //this.state.videoContext.stop()
  }
  seekVideo() {
    let videoContext = Taro.createVideoContext('taroVideo');
    videoContext.seek(20.8988888);
  }
  waiting() {
    getRuntime().showToast('视频加载中...');
  }
  render() {
    let { courseInformation, items, totalCount, currentNavId, currentPlayVideoId, isCollection, isTips, tipsText, videoSrc, current, isShare, autoplay, currentTime } = this.state;
    let teacherInfo = courseInformation.teacherInfo;
    const tabList = [{ title: '目录' }, { title: '课程详情' }, { title: '机构简介' }];
    return <View style={_styleSheet["college-course-detail"]}>

      

       

        
        <View style={_styleSheet["video-wrap"]}>
          <video style={{ width: '100%', objectFit: 'contain' }} controls autoPlay={autoplay} preload="auto" poster={courseInformation.courseLogoImg} x-webkit-airplay={true} webkit-playsinline={true} playsinline={true} x5-video-player-type="h5" x5-video-player-fullscreen={true} src={videoSrc}>
          </video>
          <View style={_styleSheet["line"]}>
            <View style={_styleSheet["title"]}>{courseInformation.courseName}</View>
            <View onClick={this.btnShare.bind(this)} style={_styleSheet["btn-share"]}>
              <Image src={share} style={_styleSheet["share-icon"]} />
              <Text style={_styleSheet["share-name"]}>分享</Text>
            </View>
          </View>
          <View style={_styleSheet["line"]}>
            <View style={_styleSheet["num"]}>{courseInformation.studyCount}人学过</View>
            <View style={_styleSheet["all"]}>共 <Text style={_styleSheet["count"]}>{items.length}</Text>个课程</View>
          </View>
        </View>
        <View style={_styleSheet["interval"]} />

        <AtTabs current={current} tabList={tabList} onClick={this.handleClick.bind(this)} style={_styleSheet["course-detail"]}>
          <AtTabsPane current={current} index={0}>
            <View style={[_styleSheet["item"], _styleSheet["catalog"]]}>
              <View style={_styleSheet["list-09"]}>
                {items.length > 0 && items.map((item, index) => {
                let tpl = null;
                if (item.isFree) {
                  tpl = <View onClick={this.setVideoSrc.bind(this, item.url, index)} style={_styleSheet["list-09-item"]}>
                        <View style={_styleSheet["line"]}>
                          <View style={_styleSheet["top"]}>
                            <View style={_styleSheet["index"]}>{this.getChapterId(index + 1)}</View>
                            <View style={_styleSheet["title"]}>{item.chaptersTitle}</View>
                            <View style={_styleSheet["try"]}>试看</View>
                          </View>
                          <View style={_styleSheet["free"]}>免费</View>
                        </View>
                        <View style={[_styleSheet["line"], _styleSheet["line2"]]}>
                          <Image src={time_long} style={_styleSheet["time-icon"]} />
                          <View style={_styleSheet["time-long"]}>56;56</View>
                        </View>
                      </View>;
                } else if (item.isBuy) {
                  tpl = <View style={_styleSheet["list-09-item"]}>
                        <View style={_styleSheet["line"]}>
                          <View style={_styleSheet["top"]}>
                            <View style={_styleSheet["index"]}>{this.getChapterId(index + 1)}</View>
                            <View style={_styleSheet["title"]}>{item.chaptersTitle}</View>
                          </View>
                          {currentPlayVideoId === index && <View onClick={this.setVideoSrc.bind(this, item.url, index)} style={[_styleSheet["free"], _styleSheet["once-play"]]}>播放中...</View>}
                          {currentPlayVideoId !== index && <View onClick={this.setVideoSrc.bind(this, item.url, index)} style={_styleSheet["free"]}>立即播放</View>}
                        </View>
                        <View style={[_styleSheet["line"], _styleSheet["line2"]]}>
                          <Image src={time_long} style={_styleSheet["time-icon"]} />
                          <View style={_styleSheet["time-long"]}>56:35</View>
                        </View>
                      </View>;
                } else {
                  tpl = <View onClick={this.buyCourse.bind(this, item.id)} style={[_styleSheet["list-09-item"], _styleSheet["list-09-item-disable"]]}>
                        <View style={_styleSheet["line"]}>
                          <View style={_styleSheet["top"]}>
                            <View style={_styleSheet["index"]}>{this.getChapterId(index + 1)}</View>
                            <View style={_styleSheet["title"]}>{item.chaptersTitle}</View>
                          </View>
                          <View style={_styleSheet["free"]}><Text style={_styleSheet["list-small"]}>￥</Text>{item.price}</View>
                        </View>
                        <View style={[_styleSheet["line"], _styleSheet["line2"]]}>
                          <Image src={time_long} style={_styleSheet["time-icon"]} />
                          <View style={_styleSheet["time-long"]}>56:35</View>
                        </View>
                      </View>;
                }
                return tpl;
              })}
                
                {items.length < totalCount && <View onClick={this.getMore.bind(this)} style={[_styleSheet["view-more"], _styleSheet["color-light"]]}>查看更多</View>}
              </View>
              <View style={_styleSheet["interval"]} />
              <View style={_styleSheet["teacher-wrap"]}>
                {teacherInfo && <View style={_styleSheet["column-title"]}>
                   <Text style={_styleSheet["column-name"]}>讲师介绍</Text>
                </View>}
                {teacherInfo && teacherInfo.map(item => {
                return <View style={_styleSheet["list-10-item"]}>
                      <Image src={item.teacherLogo} style={_styleSheet["teacher-pic"]} />
                      <View style={_styleSheet["info"]}>
                        <View style={_styleSheet["title"]}>{item.teacherName}</View>
                        <View style={_styleSheet["desc"]}>{item.teacherIntroduce}</View>
                      </View>
                    </View>;
              })}
              </View>
            </View>
          </AtTabsPane>
          <AtTabsPane current={current} index={1}>
            <View style={[_styleSheet["item"], _styleSheet["detail"], _styleSheet["rich-text"]]}>
              <RichText nodes={courseInformation.courseContent} />
            </View>
          </AtTabsPane>
          <AtTabsPane current={current} index={2}>
            <View style={[_styleSheet["item"], _styleSheet["desc"]]}>
              <View style={_styleSheet["company"]}>
                <Image src={courseInformation.mechanismLogo} style={_styleSheet["logo"]} />
                <View style={_styleSheet["info"]}>
                  <View style={_styleSheet["title"]}>{courseInformation.mechanism}</View>
                  <View style={_styleSheet["desc-info"]}>{courseInformation.introduce}</View>
                </View>
              </View>

              <View style={[_styleSheet["column-title"], _styleSheet["content-30"]]}>
                <Text style={_styleSheet["column-name"]}>机构简介</Text>
              </View>

              <View style={_styleSheet["item-lawyer-desc"]}>
                <RichText nodes={courseInformation.mechanismContent} />
              </View>

              <View style={[_styleSheet["column-title"], _styleSheet["content-30"]]}>
                <Text style={_styleSheet["column-name"]}>联系方式</Text>
              </View>

              <View style={_styleSheet["item-lawyer"]}>
                <View style={_styleSheet["line"]}>
                  <Text style={_styleSheet["title"]}>招生电话：</Text>
                  <Text style={_styleSheet["name"]}>{courseInformation.phoneNumber}</Text>
                </View>
                <View style={_styleSheet["line"]}>
                  <Text style={_styleSheet["title"]}>电子邮箱：</Text>
                  <Text style={_styleSheet["name"]}>{courseInformation.emailAddress}</Text>
                </View>
                <View style={_styleSheet["line"]}>
                  <Text style={_styleSheet["title"]}>学校网站：</Text>
                  <View style={_styleSheet["name"]}>
                    <Text>{courseInformation.webAddress}</Text>
                  </View>
                </View>
                <View style={_styleSheet["line"]}>
                  <Text style={_styleSheet["title"]}>机构地址：</Text>
                  <Text style={_styleSheet["name"]}>{courseInformation.address}</Text>
                </View>
              </View>
            </View>
          </AtTabsPane>
        </AtTabs>
        <View style={_styleSheet["footer-block"]} />
        <View style={_styleSheet["footer-block"]} />

        <View style={_styleSheet["college-footer"]}>
          <View onClick={this.toggleCollection.bind(this)} style={_styleSheet["nav"]}>
            {!isCollection && <View>
                 <Image src={iconCollection} style={[_styleSheet["nav-icon"], _styleSheet["nav-icon1"]]} />
                 <View>收藏</View>
              </View>}
            {isCollection && <View>
               <Image src={iconCollection_on} style={[_styleSheet["nav-icon"], _styleSheet["nav-icon1"]]} />
               <View>已收藏</View>
            </View>}
            <AtToast isOpened={isTips} text={tipsText} />
          </View>
          <View onClick={this.makePhone.bind(this, courseInformation.phoneNumber)} style={_styleSheet["nav"]}>
            <Image src={tel} style={[_styleSheet["nav-icon"], _styleSheet["nav-icon2"]]} />
            <View>电话咨询</View>
          </View>
          <View onClick={this.buyCourse.bind(this, 'all')} style={[_styleSheet["nav"], _styleSheet["nav-active"]]}>
            <View>购买全部课程</View>
          </View>
        </View>

        <View style={_getStyle(isShare ? 'share-arrow share-arrow-active' : 'share-arrow')}>
          <Image src={share_icon} style={_styleSheet["share-arrow-icon"]} />
          <View style={_styleSheet["con"]}>
            <View>请点击右上角</View>
            <View>通过【发送给朋友】</View>
            <View>分享给好友</View>
          </View>
          <Image onClick={this.onClose.bind(this)} src={close_icon} style={_styleSheet["close-icon"]} />
        </View>
      </View>;
  }
};
Detail = tslib_1.__decorate([inject("stores"), observer], Detail);
export default Detail;